<template>
  <div class="form__container">
    <t-loading text="加载中..." size="small" v-if="pageData.loading" />
    <div style="height: 100%; overflow: hidden">
      <t-row v-if="!pageData.loading">
        <t-col :span="2"
          ><t-tree
            :data="pageData.treeTabs"
            activable
            hover
            :expandAll="true"
            @click="handleTreeChange"
            v-model:actived="pageData.treeActiveArr"
        /></t-col>
        <t-col :span="10">
          <BasicInfo
            v-if="pageData.activeTab === 'basicinfo'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
          <Contact
            v-if="pageData.activeTab === 'contact'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
          <IndustryAndCommerce
            v-if="pageData.activeTab === 'industry'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
          <Qualifications
            v-if="pageData.activeTab === 'qualifications'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
            :mode="props.mode"
          />
          <Account
            v-if="pageData.activeTab === 'account'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
          <Remark
            v-if="pageData.activeTab === 'remark'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, defineAsyncComponent } from "vue";

// 工具函数
import { http } from "@/utils/fetch";
import { generateFormattedNumber } from "@/utils/tools";
import { v4 as uuidv4 } from "uuid";

// 动态组件
const BasicInfo = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Supplier/components/BasicInfo.vue"));
const Contact = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Supplier/components/Contact.vue"));
const IndustryAndCommerce = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Supplier/components/IndustryAndCommerce.vue")
);
const Qualifications = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Supplier/components/Qualifications.vue")
);
const Account = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Supplier/components/Account.vue"));
const Remark = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Supplier/components/Remark.vue"));
// import { deleteFileMany } from "@/api/file";

// import { useUserStore } from "@/stores/modules/user";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  mode: {
    type: String,
    required: true
  }
});

// const emits = defineEmits(["close"]);

// const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/provider/findOne"; // 查询接口
// const CREATE_FORM_PATH = "/provider/create"; // 创建接口
// const UPDATE_FORM_PATH = "/provider/update"; // 更新接口

// const userStore = useUserStore();

const pageData = reactive<Record<string, any>>({
  loading: true,
  readOnly: false,
  formData: {
    id: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    name: "",
    nickName: "",
    address: "",
    englishName: "",
    englishNickName: "",
    englishAddress: "",
    country: "",
    province: "",
    mainBusiness: "",
    market: "",
    creditCode: "",
    legalPerson: "",
    registerName: "",
    type: "",
    registerTime: "",
    registerLimitTime: [],
    registerLimitTimeStart: "",
    registerLimitTimeEnd: "",
    registerMoney: "",
    registerAddress: "",
    registerBusiness: "",
    defaultBankAccount: "",
    registerLicense: {},
    registerLicenseId: "",
    providerNo: "",
    contacts: [
      // {
      //   id: "",
      //   status: 0,
      //   hasDeleted: 0,
      //   remark: "",
      //   name: "",
      //   phone: "",
      //   department: "",
      //   wechatId: "",
      //   whatsappId: "",
      //   job: ""
      // }
    ],
    qualificationIds: [],
    qualificationFiles: [],
    banks: [],
    deletedQualFileIds: []
  },
  formRules: {},
  activeTab: "basicinfo",
  treeActiveArr: ["basicinfo"],
  treeTabs: [
    {
      label: "供应商信息",
      value: "providers",
      children: [
        {
          label: "基本信息",
          value: "basicinfo"
        },
        {
          label: "联系人信息",
          value: "contact"
        },
        {
          label: "工商信息",
          value: "industry"
        },
        {
          label: "资质文件",
          value: "qualifications"
        },
        {
          label: "账户信息",
          value: "account"
        }
      ]
    },
    {
      label: "其他信息",
      value: "others",
      children: [
        {
          label: "备注",
          value: "remark"
        }
      ]
    }
  ]
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode !== "new") {
    // } else if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;

    // 给每一个联系人本地数据加一个 localUUID，方便识别
    if (pageData.formData.contacts.length > 0 && !pageData.formData.contacts.some((item: null) => item === null)) {
      pageData.formData.contacts.forEach((item: any) => {
        item.localUUID = uuidv4();
      });
    }

    if (pageData.formData.banks.length > 0 && !pageData.formData.banks.some((item: null) => item === null)) {
      pageData.formData.banks.forEach((item: any) => {
        item.localUUID = uuidv4();
      });

      pageData.formData.deletedQualFileIds = [];
    } else {
      pageData.formData.banks = [];
    }

    if (
      pageData.formData.qualificationFiles.length === 0 &&
      pageData.formData.qualificationFiles.some((item: null) => item === null)
    ) {
      pageData.formData.qualificationFiles = [];
    }

    pageData.formData.registerLimitTime = [
      pageData.formData.registerLimitTimeStart,
      pageData.formData.registerLimitTimeEnd
    ];

    pageData.loading = false;

    if (props.mode === "view") {
      pageData.readOnly = true;
    }
  } else {
    pageData.loading = false;
    pageData.formData.providerNo = `CMM${generateFormattedNumber()}`;
  }
};

const handleTreeChange = (e: Record<string, any>) => {
  pageData.activeTab = e.node.value;
};

const handleUpdateData = (newData: Record<string, any>) => {
  pageData.formData = { ...pageData.formData, ...newData };
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
// const handleSubmit = async () => {
//   let resultData;

//   if (props.mode === "view") {
//     handleClose();
//     return;
//   }

//   // console.log(toRaw(pageData.formData));
//   const postFormData = toRaw(pageData.formData);

//   if (postFormData.banks.length === 0) {
//     MessagePlugin.error("银行信息不能为空！");
//     return;
//   }

//   if (postFormData.contacts.length === 0) {
//     MessagePlugin.error("联系人信息不能为空！");
//     return;
//   }

//   if (postFormData.qualificationFiles.length === 0) {
//     MessagePlugin.error("资质文件信息不能为空！");
//     return;
//   } else {
//     postFormData.qualificationIds = postFormData.qualificationFiles.map((item: Record<string, any>) => item.id);
//   }

//   if (postFormData.deletedQualFileIds.length > 0) {
//     await deleteFileMany({ deleteIds: postFormData.deletedQualFileIds });
//   }

//   if (props.mode === "new") {
//     // 新增
//     resultData = await http("POST", CREATE_FORM_PATH, postFormData);
//   } else {
//     // 更新
//     // postFormData.updatedTime = new Date().toISOString();
//     // postFormData.updatedBy = userStore.userData?.id;

//     resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
//   }

//   // 根据接口返回结果，提示操作成功或失败，并关闭对话框
//   if (resultData.code === 200) {
//     emits("close", "success");
//   }
// };

// const handleClose = () => {
//   // 关闭对话框，并返回取消操作标识
//   emits("close", "cancel");
// };

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
